<template>
  <!-- 短信平台 配置 -->
  <div>
    <RadioGroup v-model:value="deployType" class="deployType">
      <Radio
        v-if="!dataSourceInfo || (dataSourceInfo && dataSourceInfo.deployType === 1)"
        :value="1"
        >SAAS部署</Radio
      >
      <Radio
        v-if="!dataSourceInfo || (dataSourceInfo && dataSourceInfo.deployType === 2)"
        :value="2"
        >数据库本地部署</Radio
      >
    </RadioGroup>
    <BasicForm v-show="deployType === 1" @register="registerSaas" />
    <BasicForm v-show="deployType === 2" @register="registerLocal" />
    <Button
      v-if="
        (deployType === 1 && !hasSaasDatabase) ||
        (deployType === 2 && localConnect && !isLocalCreated)
      "
      type="primary"
      :loading="createLoading"
      @click="handleCreate"
      >创建数据库</Button
    >
  </div>
</template>

<script setup lang="ts">
  import { Button, RadioGroup, Radio } from 'ant-design-vue';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { databaseConfigSchemas } from './schemas';
  import { useMessage } from '@/hooks/web/useMessage';
  import { inject, ref, Ref } from 'vue';
  import { creatingDatabase } from '@/api/institution/list';
  import { testDB, orgDataSourceInfoVo } from '@/api/institution/list';
  import { ITestDBData } from '@/api/institution/model/listModel';

  const deployType = ref(1);

  const hasSaasDatabase = ref(false);
  const createLoading = ref(false);

  const localConnect = ref(false);
  const localData = ref<ITestDBData>();
  const isLocalCreated = ref(false);

  const schemasSaas: any = ref([]);
  const schemas: FormSchema[] = databaseConfigSchemas();

  const dataSourceInfo = ref();

  const dataId = inject('dataId') as Ref<string | number>;
  const { createMessage } = useMessage();

  const getOrgDataSourceInfoVo = async () => {
    let res = await orgDataSourceInfoVo(dataId.value);
    dataSourceInfo.value = res;
    if (!res) return;
    deployType.value = res.deployType;
    if (res.deployType === 1) {
      if (schemasSaas.value.length) return;
      schemas.forEach((schema) => {
        let obj = {
          ...schema,
          defaultValue: res?.[schema.field],
          componentProps: {
            disabled: true,
          },
        };
        schemasSaas.value.push(obj);
        appendSchemaByField(obj, '', false);
      });
      hasSaasDatabase.value = true;
    } else {
      isLocalCreated.value = true;
      setFieldsValueLocal(res);
      schemas.forEach((schema) => {
        updateSchema({
          field: schema.field,
          componentProps: {
            disabled: true,
          },
        });
      });
    }
  };

  getOrgDataSourceInfoVo();

  const [registerSaas, { validate: validateSaas, setProps: setPropsSaas, appendSchemaByField }] =
    useForm({
      schemas: schemasSaas,
      autoFocusFirstItem: true,
      actionColOptions: {
        span: 24,
      },
      labelWidth: 200,
      showSubmitButton: false,
      submitButtonOptions: {
        text: '保存',
      },
      showResetButton: false,
      submitFunc: async () => {
        try {
          const res = await validateSaas();
          console.log(res, dataId);
          setPropsSaas({
            submitButtonOptions: {
              loading: true,
            },
          });
          setTimeout(() => {
            setPropsSaas({
              submitButtonOptions: {
                loading: false,
              },
            });
            createMessage.success('提交成功！');
          }, 2000);
        } catch (error) {}
      },
    });

  const [
    registerLocal,
    {
      validate: validateLocal,
      setProps: setPropsLocal,
      setFieldsValue: setFieldsValueLocal,
      updateSchema,
    },
  ] = useForm({
    schemas,
    autoFocusFirstItem: true,
    actionColOptions: {
      span: 8,
    },
    labelWidth: 200,
    showSubmitButton: !isLocalCreated.value,
    submitButtonOptions: {
      text: '连接数据库',
    },
    showResetButton: false,
    submitFunc: async () => {
      try {
        const res = await validateLocal();
        localData.value = res;
        setPropsLocal({
          submitButtonOptions: {
            loading: true,
          },
        });
        await testDB(res);
        localConnect.value = true;
        setPropsLocal({
          submitButtonOptions: {
            loading: false,
          },
        });
        createMessage.success('连接成功！');
      } catch (error) {
        setPropsLocal({
          submitButtonOptions: {
            loading: false,
          },
        });
      }
    },
  });

  const handleCreate = async () => {
    try {
      createLoading.value = true;
      await creatingDatabase({
        ...localData.value,
        orgId: dataId.value,
        deployType: deployType.value,
      });
      createLoading.value = false;
      if (deployType.value === 1) {
        hasSaasDatabase.value = true;
        getOrgDataSourceInfoVo();
      } else {
        localConnect.value = true;
        isLocalCreated.value = true;
      }
      createMessage.success('创建成功！');
    } catch (error) {
      createLoading.value = false;
    }
  };
</script>

<style lang="less" scoped>
  .deployType {
    margin-left: 100px;
    margin-bottom: 20px;
  }
</style>
